package com.ssms.exception;

import com.ssms.common.R;
import com.ssms.common.ResponseDataEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(ParamException.class)
    public R paramException(ParamException paramException){
        ResponseDataEnum responseDataEnum = paramException.getResponseDataEnum();
        if (responseDataEnum != null){
            return R.error(responseDataEnum);
        }
        return R.error(500,paramException.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R exception(Exception e){
        LOGGER.error("================系统发生了错误==========");
        LOGGER.error("发生错误的原因：{}",e.getMessage());
        LOGGER.error("异常链为   ",e.getCause());
        e.printStackTrace();
        return R.error(ResponseDataEnum.SYSTEM_ERROR);
    }

    /**
     * @Description: 异常处理方法
     * @param
     * @return: cn.swust.common.R<java.lang.String>
     * @Author: fap
     * @Date: 2022/9/24 16:35
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2]+"已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * @description: 用来处理NotNullException
     * @author: Tang
     * @date: 2022/10/19 21:33
     * @param: [ne]
     * @return: cn.swust.common.R<java.lang.String>
     **/
    @ExceptionHandler(NotNullException.class)
    public R<String> NotNullExceptionHandler(NotNullException ne) {
        log.error(ne.getMessage());
        return R.error(ne.getMessage());
    }
    /**
     * @description: 用来处理AuthenticationException
     * @author: Tang
     * @date: 2022/10/20 11:26
     * @param: [ae]
     * @return: cn.swust.common.R<java.lang.String>
     **/
    @ExceptionHandler(AuthenticationException.class)
    public R<String> AuthenticationExceptionHandler(AuthenticationException ae) {
        log.error(ae.getMessage());
        return R.error(ae.getMessage());
    }
}
